/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/update-bits
   @Language: C++
   @Datetime: 16-02-09 08:49
   */

// Method 1
class Solution {
public:
	/**
	 * @param n, m: Two integer
	 * @param i, j: Two bit positions
	 * return: An integer
	 * Tip: construct bits which range [j,i] is 0, others is 1
	 *      make AND with n, means clean rnage[j,i] as 0.
	 *      make OR with m which left move by step i bits.
	 */
	int updateBits(int n, int m, int i, int j) {
		// write your code here
		// clean range [j,i], (set [j,i] to 0, others to 1)
		n &= ~(((j-i+1>31?-1:1<<(j-i+1))-1)<<i);
		return n|(m<<i);
	}
};

// Method 2
class Solution {
public:
	/**
	 * @param n, m: Two integer
	 * @param i, j: Two bit positions
	 * return: An integer
	 */
	int updateBits(int n, int m, int i, int j) {
		// write your code here
		// split low and high, make OR with m<<i
		int low = n & ((1<<i)-1);
		int high = (j>30 ? 0: (n>>(j+1))<<(j+1));
		return high | (m<<i) | low;
	}
};
